import { localStg } from "@/utils";
import { useAuthStore } from "@/store";
import { authApi } from "@/api";

const TOKEN_KEY = "access_token";
const TOEKN_DURATION = 24 * 60 * 60;

class TokenUtils {
  token?: string;

  get = () => {
    if (this.token) return this.token;
    return localStg.get(TOKEN_KEY) as string | null;
  };

  set = (token: string) => {
    this.token = token;
    localStg.set(TOKEN_KEY, token, TOEKN_DURATION);
  };

  remove = () => {
    this.token = undefined;
    localStg.remove(TOKEN_KEY);
  };

  refresh = async () => {
    const userStore = useAuthStore();
    const expire = localStg.getExpire(TOKEN_KEY);
    if (expire <= 0) {
      this.token = undefined;
      window.$message?.error("登录已失效，请重新登录");
      console.error("token已过期，请重新登录");
      userStore.reLogin();
      return;
    }

    // 有效时间还剩余一半多则不执行刷新
    if (expire > TOEKN_DURATION / 2) return;

    try {
      const { data } = await authApi.refreshToken();
      this.token = data.token;
      tokenUtils.set(data.token);
    } catch (err) {
      // 刷新失败重新登录
      this.token = undefined;
      console.error("token刷新失败");
      userStore.reLogin();
    }
  };
}

export const tokenUtils = new TokenUtils();
